package parkshop.pmcourse.utils;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import parkshop.pmcourse.dto.User;


public class SendMailThread extends Thread {
	private User user;
	private String hostName;
	private int port;
	public SendMailThread(User user,String hostName,int port){
		this.user = user;
		this.hostName=hostName;
		this.port=port;
	}
	@Override
	public void run() {
		//发送邮件
		try {
			Properties props = new Properties();
			props.setProperty("mail.transport.protocol", "smtp");//发送使用的协议
			props.setProperty("mail.host", "smtp.sina.com");//发送服务器的主机地址
			//props.setProperty("mail.host", "localhost");//发送服务器的主机地址
			props.setProperty("mail.smtp.auth", "true");//请求身份验证
			Session session = Session.getDefaultInstance(props);
			session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress("uchiyou@sina.com"));
			//message.setFrom(new InternetAddress("system@parknshop.com"));
			message.setRecipients(Message.RecipientType.TO, user.getMail());
			message.setSubject("Thanks for sign up Parknshop");
			
			MimeBodyPart part = new MimeBodyPart();
			part.setContent(" This is an email from parkshop system！<br/>" +
					"please click link <a href='http://"+this.hostName+":"+this.port+"/activeUser/"+user.getType()+"?code="+user.getActiveCode()+"'>【parkshop】</a> to activate your account<br/>" +
							"This is a system auto_send email,do not repley the email", "text/html;charset=UTF-8");
			
			MimeMultipart mpart = new MimeMultipart();
			mpart.addBodyPart(part);
			message.setContent(mpart);
			message.saveChanges();
			
			Transport ts = session.getTransport();
			ts.connect("uchiyou@sina.com", "parknshop123");
			//ts.connect("system@parknshop.com", "123");
			ts.sendMessage(message,message.getAllRecipients());
			ts.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}
	
}
